package com.datamation.swadeshi.control.data;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.datamation.swadeshi.model.FItenrDet;

public class FItenrDetDS {
	
	private SQLiteDatabase dB;
	private DatabaseHelper dbHelper;
	Context context;
	private String TAG="swadeshi";
	
	public FItenrDetDS (Context context){
		this.context = context;
		dbHelper = new DatabaseHelper(context);
	}
	
	public void open() throws SQLException {
		dB = dbHelper.getWritableDatabase();
	}
	
	@SuppressWarnings("static-access")
	public int createOrUpdateFItenrDet(ArrayList<FItenrDet>  list) {
		int count =0;		
		if(dB == null){
			open();
		}else if(!dB.isOpen()){
			open();
		}
		Cursor cursor = null;
		
	try{
		for (FItenrDet fItenrDet : list) {
			
		ContentValues values = new ContentValues();
	
		values.put(dbHelper.FITENRHED_COST_CODE, fItenrDet.getFITENRDET_NO_OUTLET());
		values.put(dbHelper.FITENRHED_DEAL_CODE, fItenrDet.getFITENRDET_NO_SHCUCAL());
		values.put(dbHelper.FITENRHED_MONTH, fItenrDet.getFITENRDET_RD_TARGET());
		values.put(dbHelper.FITENRHED_REF_NO, fItenrDet.getFITENRDET_REF_NO());
		values.put(dbHelper.FITENRHED_REMARKS1, fItenrDet.getFITENRDET_REMARKS());
		values.put(dbHelper.FITENRHED_REP_CODE, fItenrDet.getFITENRDET_ROUTE_CODE());
		values.put(dbHelper.FITENRHED_YEAR, fItenrDet.getFITENRDET_TXN_DATE());
		
		count = (int) dB.insert(dbHelper.TABLE_FITENRDET, null, values);
	
		}
		}finally {  
			if (cursor !=null) {
				cursor.close();
			}
			dB.close();
		}
		return count;
	}

	@SuppressWarnings("static-access")
	public int deleteAll(){
		int count =0;
		
		if(dB == null){
			open();
		}else if(!dB.isOpen()){
			open();
		}
		Cursor cursor = null;
		try{
			cursor = dB.rawQuery("SELECT * FROM " + dbHelper.TABLE_FITENRDET, null);
			count =cursor.getCount();
			if(count>0){
				int success = dB.delete(dbHelper.TABLE_FITENRDET, null, null);
				Log.v("Success", success+"");
			}
		}catch (Exception e){

			Log.v(TAG+" Exception", e.toString());
			
		}finally{  
			if (cursor !=null) {
				cursor.close();
			}
			dB.close();
		}
		
		return count;
		
	}
}
